﻿package com.wly.ui
{
	import com.wly.ui.common.IItemGrid;
	import com.wly.ui.common.SpriteObject;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	
	public class ItemCell extends SpriteObject
	{
		private var _index:int = -1;
		private var _parentUI:IItemGrid;
		private var _mcStatus:MovieClip;
		private var _isSelected:Boolean;
		private var _bmpArr:Array;
		
		static public const HIGHT:int = 32;
		static public const WIDTH:int = 32;
		
		public function ItemCell()
		{
			super();
			
			_bmpArr = [];
			_mcStatus = getChildByName("mcStatus") as MovieClip;
			_mcStatus.stop();
			_mcStatus.mouseEnabled  = false;
			_mcStatus.mouseChildren = false;
			//addEventListener(MouseEvent.CLICK, onClick);
			addEventListener(MouseEvent.ROLL_OVER, onOver);
			addEventListener(MouseEvent.ROLL_OUT, onOut);
			addEventListener(MouseEvent.MOUSE_DOWN, onDown);
		}
		
		public function set parentUI(parentUI:IItemGrid):void
		{
			_parentUI = parentUI;
		}
		
		public function set index(val:int):void
		{
			_index = val;
		}
		
		public function updateBmd(bmd:BitmapData, index:int=0):void
		{
			var bmp:Bitmap = _bmpArr[index] as Bitmap;
			if(bmp == null)
			{
				bmp = new Bitmap;
				_bmpArr[index] = bmp;
				addChildAt(bmp, index);
			}
			bmp.bitmapData = bmd;
		}
		
		public function clearBmd():void
		{
			graphics.clear();
		}
		
		private function onClick(e:MouseEvent):void
		{
			if(_parentUI)
			{
				_parentUI.onSelect(_index);
			}
		}
		
		private function onOver(e:MouseEvent):void
		{
			scaleX = 1.1;
			scaleY = 1.1;
			_mcStatus.gotoAndStop(2);
			if(_parentUI)
			{
				_parentUI.setTop(this);
				_parentUI.onItemMouseOver(_index);
			}
		}
		
		private function onOut(e:MouseEvent):void
		{
			scaleX = 1;
			scaleY = 1;
			_mcStatus.gotoAndStop(1);
		}
		
		private function onDown(e:MouseEvent):void
		{
			if(_parentUI)
			{
				_parentUI.onSelect(_index);
			}
		}
		
		public function set select(selected:Boolean):void
		{
			if(selected)
			{
				_mcStatus.gotoAndStop(2);
			}
			else
			{
				_mcStatus.gotoAndStop(1);
			}
		}
		
		public function disableMouseOver():void
		{
			removeEventListener(MouseEvent.ROLL_OVER, onOver);
			removeEventListener(MouseEvent.ROLL_OUT, onOut);
		}
		
		public function getBmd(index:int=0):BitmapData
		{
			var bmp:Bitmap = _bmpArr[index] as Bitmap;
			if(bmp)
			{
				return bmp.bitmapData;
			}
			return null;
		}
	}
}